<?php
declare (strict_types=1);

namespace app\adminapi\controller\v1\user;

use think\Request;
use app\common\controller\AdminController;

class UserGroup extends AdminController
{
    /**
     * @var \app\common\model\user\UserGroup
     */
    public $model;

    public function initialize()
    {
        $this->model = new \app\common\model\user\UserGroup();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = $this->model->where([])->select();
        return $this->success("ok", $list);
    }



    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $data = $this->model->where(['id' => $id])->find();
        $data['type'] = in_array($data['type'], ['primary','info','danger','success','warning'])?$data['type']:'primary';
        return $this->success("", $data);
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $formData = $request->post('formData');
        $userGroup = $this->model->where(['id' => $id])->find();
        if (!$userGroup) {
            return $this->error("用户组不存在");
        }
        if (!$formData['group_name']) {
            return $this->error("用户组名不能为空");
        }
        $userGroup->save($formData);
        return $this->success("更新成功" , $formData);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $formData = $request->post('formData');
        if (!$formData['group_name']) {
            return $this->error("用户组名不能为空");
        }
        $this->model->save($formData);
        return $this->success("新增成功");
    }



    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $this->model->where(['id' => $id])->delete();
        return $this->success("删除成功");
    }
}
